import os
import json
import numpy as np
import logging as logger
from typing import Union

logger.basicConfig(level=logger.DEBUG)

def _default_dum(obj):
    if isinstance(obj,(np.integer,np.float_,np.double,np.bool_)):
        return obj.item()
    elif isinstance(obj,np.ndarray()):
        return obj.tolist()
    else:
        return obj

def jopen(filedir:str,mode:str,loadmode="all",dumpmode="all",wdatas:Union[dict,list]=None,encoding="utf-8"):
    """json文件操作方法

    Args:
        filedir (str): 读取或写入的json文件
        mode (str): 读、写或追加. "r" 、"w" or "a".
        loadmode (str, optional): 读取模式. Defaults to "all"-全文读取,"line"-按行读取.
        dumpmode (str, optional): 写入模式. Defaults to "all"-全文写入,"line"-按行写入.
        wdatas (dict | list, optional): 需要写入的数据，支持写入字典或字典列表. Defaults to None.
        encoding (str, optional): 编码. Defaults to "utf-8".

    Returns:
    """
    if mode == "r":
        
        if loadmode == "all":
            with open(filedir,mode=mode,encoding=encoding) as f:
                return json.load(f)
            
        elif loadmode == "line":
            jdatas=[]
            lines=[]
            with open(filedir,mode=mode,encoding=encoding) as f:
                lines=f.readlines()
                
            for line in lines:
                logger.debug("json load data:%s",line)
                jdatas.append(json.loads(line))
                
            return jdatas
        
    elif mode in ["w","a"]:
        
        if dumpmode == "all":
            
            with open(filedir,mode=mode,encoding=encoding) as f:
                json.dump(wdatas,f,indent=4,ensure_ascii=False,default=_default_dum)
                
        elif dumpmode == "line":
            
            with open(filedir,mode=mode,encoding=encoding) as f:
                
                if type(wdatas) == dict:
                    logger.debug("json dump data:%s",wdatas)
                    f.write(json.dumps(wdatas,ensure_ascii=False,default=_default_dum)+"\n")
                    
                elif type(wdatas) == list:
                    
                    for wd in wdatas:
                        logger.debug("json dump data:%s",wd)
                        f.write(json.dumps(wd,ensure_ascii=False,default=_default_dum)+"\n")

def topen(filedir:str,mode:str,rmode="all",wdatas:Union[str,list]=None,encoding="utf-8"):
    """txt文件操作方法

    Args:
        filedir (str): 读取或写入的txt文本文件
        mode (str): 读、写或追加. "r" 、"w" or "a".
        rmode (str, optional): 读取模式. Defaults to "all"-全文读取返回str,"line"-按行读取,返回list
        wdatas (str | list, optional): 需要写入的数据，支持写入字符串或字符串列表. Defaults to None.
        encoding (str, optional): 编码. Defaults to "utf-8".

    Returns:
        _type_: _description_
    """
    
    if mode == "r":
    
        if rmode == "all":
            con=""
    
            with open(filedir,mode=mode,encoding=encoding) as f:
                con=f.read()
            
            return con
        
        elif rmode == "line":
            
            lines=[]
            with open(filedir,mode=mode,encoding=encoding) as f:
                lines=f.readlines()
            
            return lines
                        
    elif mode in ["w","a"]:
        
        if type(wdatas) == str:
            with open(filedir,mode=mode,encoding=encoding) as f:
                f.write(wdatas)
        elif type(wdatas) == list:
            with open(filedir,mode=mode,encoding=encoding) as f:
                con=""
                for c in wdatas:
                    con+=c+"\n"
                con=con.strip()
                f.write(con)
            
def father_dir(dir:str)->str:
    """获取父路径

    Args:
        dir (str): 子路径

    Returns:
        str: 父路径
    """
    return os.path.dirname(dir)

def basename(dir:str,with_suffix=True)->str:
    """获取文件名

    Args:
        dir (str): 文件路径
        with_suffix (bool, optional): 是否带文件后缀. Defaults to True.

    Returns:
        str: 返回基础文件名
    """
    basename_with_suffix=os.path.basename(dir)
    if not with_suffix:
        (basename,tail) = os.path.splitext(basename_with_suffix)
        return basename        
    else:
        return basename_with_suffix
